import React, { useEffect, useState } from "react";
import { ListRes, VedioListItem } from "./dto";
import { getImagesFromVedio } from "./utils";
import styles from "./index.module.less";
import { Link, useHistory, useParams } from "react-router-dom";
import { Select, Pagination } from "antd";
import { DefaultOptionType } from "antd/lib/select";

const getList = (tag, p) => {
  return fetch(`/api/locallist/${p ?? "1"}/${tag ?? ""}`).then((res) =>
    res.json()
  );
};

const getTags = () => {
  return fetch("/api/tags").then((res) => res.json());
};

function forma2(num) {
  return (
    "0".repeat(2 - String(Math.floor(num / 3600)).length) +
    Math.floor(num / 3600) +
    ":" +
    "0".repeat(2 - String(Math.floor((num % 3600) / 60)).length) +
    Math.floor((num % 3600) / 60) +
    ":" +
    "0".repeat(2 - String(Math.floor((num % 3600) % 60)).length) +
    Math.floor((num % 3600) % 60)
  );
}

const List = () => {
  const [list, setList] = useState<VedioListItem[]>([]);
  const [total, setTotal] = useState(0);
  const [tag, setTag] = useState("");

  const [options, setOptions] = useState<DefaultOptionType[]>();

  const { pageIndex = "1" } = useParams<{ pageIndex: string }>();

  console.log({ pageIndex });

  const history = useHistory();

  const fetchList = (tag?: string) => {
    getList(tag, pageIndex).then((res: ListRes) => {
      const l =
        res.data?.list?.map<VedioListItem>((m) => ({
          name: m.name,
          id: m.sha256,
          image: getImagesFromVedio(m.sha256)[0],
          time: m.time,
          size: m.size,
        })) ?? [];
      setList(l);
      setTotal(res.data?.total ?? 0);
    });
  };

  useEffect(() => {
    getTags().then((res) => {
      setOptions(
        res.map((m) => {
          return {
            label: m,
            value: m,
          };
        })
      );
    });
  }, []);

  useEffect(() => {
    fetchList(tag);
  }, [pageIndex, tag]);

  return (
    <div className={styles["container"]}>
      <div className={styles.nav}>
        家庭影院
        <Select
          placeholder="请选择"
          style={{ width: "100px" }}
          options={options}
          onChange={(e) => {
            setTag(e);
            history.push(`/list/1`);
          }}
        />
      </div>
      <div className={styles["list-container"]}>
        {list.map((m) => {
          return (
            <div key={m.id} className={styles["list-item"]}>
              <Link to={`/detail/${m.id}`} target="_blank">
                <div className={styles["img-wrap"]}>
                  <img src={`/images/${m.image}`} alt="" />
                  <div className={styles.tz}>
                    {m.size && <span className={styles["time"]}>{m.size}</span>}
                    {m.time && (
                      <span className={styles["time"]}>{forma2(m.time)}</span>
                    )}
                  </div>
                </div>
                <div className={styles["list-title"]}>
                  <span>{m.name}</span>
                </div>
              </Link>
            </div>
          );
        })}
      </div>
      <div className={styles["list-page"]}>
        <Pagination
          current={parseInt(pageIndex)}
          pageSize={20}
          total={total}
          onChange={(p) => {
            history.push(`/list/${p}`);
          }}
        />
      </div>
    </div>
  );
};

export default List;
